package club.justwill.single.persistence.dao;

import club.justwill.single.persistence.jpo.Activity;
import club.justwill.single.persistence.support.BaseDao;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import java.util.Collection;
import java.util.List;

/**
 * Created by xiangnan on 16-1-15.
 */
@Repository
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ActivityDao extends BaseDao<Activity> {

    public List getByUserId(Long userId) {
        return em.createNamedQuery("Activity.getByUserId").setParameter("userId", userId).getResultList();
    }

    public Activity getByActId(Long ActivityId) {
        Query query = em.createNamedQuery("Activity.getByActivityId").setParameter("activityId", ActivityId);
        try {
            return (Activity) query.getSingleResult();
        } catch (NonUniqueResultException e) {
            return (Activity) query.getResultList().get(0);
        } catch (NoResultException e) {
            return null;
        }
    }

    public List getByActIdList(Collection list) {
        return em.createNamedQuery("Activity.getByActivityIds").setParameter("activityIds", list).getResultList();
    }

    public List<Activity> searchActivity(int index, int size) {

        Query query = em.createNamedQuery("Activity.searchActivity").setFirstResult(index).setMaxResults(size);
        return query.getResultList();
    }
}
